<?php


namespace lib;


//use app\common\model\Org;
use think\Exception;
//use think\Env;

class Ekfapi
{
    // 表单提交字符集编码
    private $postCharset = "UTF-8";

    private $fileCharset = "UTF-8";
    private $store_id    = '2020102714462478798';//门店id
    private $key         = 'jc3kRoDInvmKkQ5lGrd64ylxd9tX91mqzKg08mmX6P9';//秘钥
    private $base_url    = 'https://device.xinyaoan.com/';
    private $public_key  = 'rm2RQBdxzW5kRKHLKcHkN6XIlUXA1UBBumxv25IWvES';
    private $is_mini         = '';//是否小程序支付  0=不是  1=是
    private $wx_appid         = '';//小程序或者公众号appid


    public function __construct($community_id = null) {

//        $this->base_url = Env::get('app.pdsurl','https://card.pdsyun.com/');
//        if($community_id){
//            $community = Org::get($community_id);
        $this->store_id = '110091751334465';
        $this->key      = '7fTp2Ks9XmV4nRz6Lq8Gy3hBj1wDc5NxP';
//        }
    }

    public function curl_get($url, $data) {
        $ch     = curl_init();
        $header = ['Content-type: application/json'];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }

    //提交数据sha1加密
    public function get_data($data) {
        $key          = $this->key;
        $string       = $this->getSignContent($data) . '&key=' . $key;
        $data['sign'] = sha1($string);

        return json_encode($data);
    }

    //校验sha1
    public function check_sha1($data) {
        $key          = $this->key;
        $sign         = $data['sign'];
        $data['sign'] = null;
        $string       = $this->getSignContent($data) . '&key=' . $key;

        if ($sign == sha1($string)) {
            return [
                'code' => 1,
                'msg'  => '验证通过'
            ];
        } else {
            return [
                'code' => 0,
                'msg'  => '验证不通过'
            ];
        }
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    public function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }

    //参数拼接
    public function getSignContent($params) {
        ksort($params);

        $stringToBeSigned = "";
        $i                = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {

                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);

        return $stringToBeSigned;
    }

    public function pre_pay($order_data,$attach = ''){
        $api_url = $this->base_url.'api/services/payapi/prePay';
//        halt($api_url);
        $data = [
            'store_code' => $this->store_id,//门店id
            'buyer_id' => $order_data['openid'],//用户唯一标识
            'type_source' => $order_data['type_source']??'weixin',//alipay=支付宝  weixin=微信
            'total_amount' =>$order_data['money'],//支付金额
            'out_trade_no' => $order_data['order_no'],//订单号
            'shop_body' => $order_data['goods_title'],//商品名称
            'attach' => $attach, //附加信息，原样返回
            'is_mini'=>0,
            'wx_appid'=>'',
        ];
        if(isset($order_data['return_url']))$data['return_url'] = $order_data['return_url'];
        log_write('发送参数=='.json_encode($data));
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return json_decode($res,true);
    }

    /**
     * Name 被扫支付
     * @param $code  //付款码
     * @param $money //金额
     * @param $order_no //订单号
     * @return mixed
     */
    public function trade_pay($order_data)
    {
        $api_url = $this->base_url.'api/services/payapi/tradePay';
        $data = [
            'store_code' => $this->store_id,//门店id
            'code'=>$order_data['code'],//付款码
            'total_amount' =>$order_data['total_amount'],//支付金额
            'shop_price' =>$order_data['shop_price']??'',//商品原价格
            'shop_body' =>$order_data['shop_body']??'',//商品名称
            'out_trade_no' => $order_data['out_trade_no'],//订单号
            'equipid' => $order_data['equipid'],//终端编号
        ];
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return json_decode($res,true);
    }

    /**
     * Name 被扫支付
     * @param $code  //付款码
     * @param $money //金额
     * @param $order_no //订单号
     * @return mixed
     */
    public function quick_pay($code,$money,$order_no)
    {
        $api_url = $this->base_url.'payapi/quickPayRequest';
        $data = [
            'store_id' => $this->store_id,//门店id
            'code'=>$code,
            'total_amount' =>$money,//支付金额
            'out_trade_no' => $order_no,//订单号
        ];
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return json_decode($res,true);
    }

    public function fast_pay($order_data,$attach = ''){
        $api_url = $this->base_url.'payapi/quickPayRequest';
        $data = [
            'store_id' => $this->store_id,//门店id
            'buyer_id'=>$order_data['openid'],
            'type_source' => $order_data['type_source']??'weixin',//alipay=支付宝  weixin=微信
            'total_amount' =>$order_data['money'],//支付金额
            'out_trade_no' => $order_data['order_no'],//订单号
            'shop_body' => $order_data['goods_title'],//商品名称
            'attach' => $attach,//商品名称
            'return_url' => $order_data['return_url']??null,//商品名称
            'is_js' => 1
        ];
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return $res;
    }

    /**
     * Name 订单查询
     * @param $order_no //订单号
     * @return mixed
     */
    public function order_query($order_no)
    {
        $api_url = $this->base_url.'api/services/payapi/orderQuery';
        $data = [
            'store_code' => $this->store_id,//门店id
            'out_trade_no'=>$order_no,
        ];
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return json_decode($res,true);
    }

    /**
     * Name 退款
     * @param $order_no //订单号
     * @return mixed
     */
    public function refund($order_data)
    {
        $api_url = $this->base_url.'api/services/payapi/refund';
        $data = [
            'store_code' => $this->store_id,//门店id
            'out_trade_no'=>$order_data['out_trade_no'],
            'refund_amount'=>$order_data['refund_amount']
        ];
        // \think\Log::info('api_url=='.$api_url);
        // \think\Log::info('data数据=='.json_encode($data));
        log_write('data数据=='.json_encode($data));
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return json_decode($res,true);
    }


    /**
     * Name 退款查询
     * @param $order_no //订单号
     * @return mixed
     */
    public function refundOrderQuery($order_no)
    {
        $api_url = $this->base_url.'api/services/payapi/refundQuery';
        $data = [
            'store_code' => $this->store_id,//门店id
            'back_order_no'=>$order_no,
        ];
        $data = $this->get_data($data);
        $res = $this->curl_get($api_url,$data);
        return json_decode($res,true);
    }
    /**
     * 图片上传
     * @param $url
     * @param $data
     * @return bool|string
     */
    public function curl_upload($data)
    {
        $url = $this->base_url.'goldapi/upload';
        $key          = $this->public_key;
        $string       = $this->getSignContent($data) . '&key=' . $key;
        $data['sign'] = sha1($string);

        $path = $data['path'];

        $ch = curl_init();
        try{
            if (class_exists('\CURLFile')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
                $data['file'] = new \CURLFile(realpath($path));//>=5.5
            } else {
                if (defined('CURLOPT_SAFE_UPLOAD')) {
                    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
                }
                $data['file'] = '@' . realpath($path);//<=5.5
            }
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);

            //释放curl句柄
            curl_close($ch);
        }catch (Exception $e){
            $output = ['code' => 0,'msg' => $e->getMessage()];
            return $output;
        }
        return json_decode($output,true);
    }
}